//
//  SearchChatRoomMemberViewController.m
//  MyYiJianKangApp
//
//  Created by 张国文 on 16/4/11.
//  Copyright © 2016年 hangzhouyijiyin. All rights reserved.
//

#import "SearchChatRoomMemberViewController.h"
#import "CeShiModelOfFriendMessage.h"
#import "FriendMessageTableViewCell.h"
#import "MyChatViewController.h"
#import "ZGWSearchFriendModel.h"
#import "FriendIDCheckViewController.h"

#define kCurrentUserToken [[NSUserDefaults standardUserDefaults]objectForKey:@"token"]
@interface SearchChatRoomMemberViewController ()<UITableViewDataSource, UITableViewDelegate, UISearchBarDelegate>

@property (nonatomic, strong) UISearchBar *mySearchBar;
@property (nonatomic, strong) UITableView *myFriendTableView;
@property (nonatomic, strong) NSMutableArray *myFriendDataArray; // 数据源数组
@property (nonatomic, assign) BOOL isHaveData; // 判断时候有数据
@property (nonatomic, assign) BOOL canClickGuanZhu; // 是否可以点击关注
@property (nonatomic, assign) BOOL shouldRefreshWhenReturnLastPage; // 返回上一页是否需要刷新

@end

@implementation SearchChatRoomMemberViewController

- (void)viewWillDisappear:(BOOL)animated
{
    [[JiaZaiAnimationHandle shareJiaZaiAnimationHandle] stopAnimation];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    // navi的修改
    [self changeNavigation];
    // 添加searchBar
    [self addSearchBar];

    // 布局
    [self addMySubview];
    self.canClickGuanZhu = YES;
    
    // 默认为不需要刷新
    self.shouldRefreshWhenReturnLastPage = NO;
}

// navi的修改
- (void)changeNavigation
{
    [self.navigationController.navigationBar setTranslucent:NO];
    self.navigationController.navigationBar.barStyle=UIBarStyleBlack;
    self.navigationController.navigationBar.titleTextAttributes = @{NSForegroundColorAttributeName:[UIColor whiteColor],NSFontAttributeName:[UIFont boldSystemFontOfSize:25]};
    [self.navigationController.navigationBar setBarTintColor:[UIColor colorWithRed:84 / 255.0 green:199 / 255.0 blue:222 / 255.0 alpha:1]];
    UIImageView *leftImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 30, 30)];
    leftImageView.image = [UIImage imageNamed:@"houtui"];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:leftImageView];
    UITapGestureRecognizer *leftTapGes = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(lastPage:)];
    [leftImageView addGestureRecognizer:leftTapGes];
    
}

#pragma mark - 返回上一页面
- (void)lastPage:(UITapGestureRecognizer *)tapGes
{
    if (self.shouldRefreshWhenReturnLastPage == YES) {
        self.zgwSearchChatRoomBlock(@"1");
    }
    [self dismissViewControllerAnimated:YES completion:nil];
}

// 添加searchBar
- (void)addSearchBar
{
    self.mySearchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, 260 * kAdjustParamater, 30 * kAdjustParamater)];
    self.mySearchBar.barStyle = UIBarStyleDefault;
    self.mySearchBar.delegate = self;
    self.mySearchBar.placeholder = @"输入聊天室成员名字";
    self.mySearchBar.tintColor = kCyanColor;
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 260 * kAdjustParamater, 30 * kAdjustParamater)];
    view.backgroundColor = [UIColor clearColor];
    view.userInteractionEnabled = YES;
    [view addSubview:_mySearchBar];
    self.navigationItem.titleView = view;
}

#pragma mark - UISearchBar代理
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    // 在每次内容改的情况下初始化数据源数组
    self.myFriendDataArray = [NSMutableArray array];

    NSArray *tempArray = [NSArray arrayWithArray:self.dataArray];
    for (ZGWSearchFriendModel *model in tempArray) {
        if ([model.nikename containsString:searchText]) {
            [self.myFriendDataArray addObject:model];
        }
    }
    // 判断是否有数据
    if (self.myFriendDataArray.count > 0) {
        // 说明有数据
        self.isHaveData = YES;
    } else {
        // 说明没有数据
        self.isHaveData = NO;
    }
    [self.myFriendTableView reloadData];
    
}

// 取消键盘
-  (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    [searchBar resignFirstResponder];
}

#pragma mark - 建立数据源
- (void)addData
{
    
}

#pragma mark - 布局
- (void)addMySubview
{
    self.myFriendTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight  - 64) style:UITableViewStylePlain];
    self.myFriendTableView.backgroundColor = [UIColor whiteColor];
    self.myFriendTableView.dataSource = self;
    self.myFriendTableView.delegate = self;
    self.myFriendTableView.bounces = NO;
    self.myFriendTableView.showsHorizontalScrollIndicator = NO;
    [self.view addSubview:_myFriendTableView];
    self.myFriendTableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
    
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.myFriendDataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identifier = @"myFriendCell";
    FriendMessageTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        cell = [[FriendMessageTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    // 获得model
    if (self.myFriendDataArray.count > indexPath.row) {
        cell.zgwSearchFriendModel = self.myFriendDataArray[indexPath.row];
    }
    
    [cell.attentionButton addTarget:self action:@selector(clickButton:) forControlEvents:UIControlEventTouchUpInside];
    cell.attentionButton.tag = 200;
    [cell.addFriendButton addTarget:self action:@selector(clickButton:) forControlEvents:UIControlEventTouchUpInside];
    cell.addFriendButton.tag = 201;
    return cell;
}

#pragma mark - 关注
- (void)clickButton:(UIButton *)button
{
    UIView *tempView = [button superview];
    FriendMessageTableViewCell *cell = (FriendMessageTableViewCell *)[tempView superview];
    NSIndexPath *tempIndexPath = [self.myFriendTableView indexPathForCell:cell];
  //  NSLog(@"row = %ld", tempIndexPath.row);
    // 获得cell
    ZGWSearchFriendModel *model = self.myFriendDataArray[tempIndexPath.row];
    
    
    switch (button.tag) {
        case 200:
        {
            // 说明是关注
            NSLog(@"关注：row = %ld, name = %@",tempIndexPath.row, model.nikename);
            ZGWSearchFriendModel *searchModel = self.myFriendDataArray[tempIndexPath.row];
            NSString *isAttention = [NSString stringWithFormat:@"%@", searchModel.is_attention];
            if ([isAttention isEqualToString:@"1"]) {
                NSLog(@"已经关注");
            } else if ([isAttention isEqualToString:@"0"]) {
                NSLog(@"进行关注");
                if (self.canClickGuanZhu == YES) {
                    self.canClickGuanZhu = NO;
                    [[JiaZaiAnimationHandle shareJiaZaiAnimationHandle] startAnimation];
                    // 关注url
                    NSString *attentionUserUrl = [NSString stringWithFormat:@"%@?token=%@", kZGWAttentionUser, kCurrentUserToken];
                    NSDictionary *paramaterDic = @{@"attention_user":searchModel.user_id};
                    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
                    [manager POST:attentionUserUrl parameters:paramaterDic success:^(NSURLSessionDataTask *task, id responseObject) {
                        [[JiaZaiAnimationHandle shareJiaZaiAnimationHandle] stopAnimation];
                        self.canClickGuanZhu = YES;
                        NSDictionary *statusDic = [responseObject valueForKey:@"status"];
                        NSString *msgString = [statusDic valueForKey:@"msg"];
                        if ([msgString isEqualToString:@"关注成功"]) {
                            searchModel.is_attention = [NSString stringWithFormat:@"%d", 1];
                            [self.myFriendTableView reloadData];
                            self.shouldRefreshWhenReturnLastPage = YES;
                        }
                    } failure:^(NSURLSessionDataTask *task, NSError *error) {
                        [[JiaZaiAnimationHandle shareJiaZaiAnimationHandle] stopAnimation];
                        [[JiaZaiAnimationHandle shareJiaZaiAnimationHandle] addAlertTitle:@"提醒" Content:@"关注失败" ToView:self];
                        self.canClickGuanZhu = YES;
                    }];
                }
            }
            break;
        }
            case 201:
        {
            // 说明是加好友
            NSLog(@"加好友：row = %ld, name = %@",tempIndexPath.row, model.nikename);
            ZGWSearchFriendModel *searchModel = self.myFriendDataArray[tempIndexPath.row];
            NSString *isFriend = [NSString stringWithFormat:@"%@", searchModel.is_friend];
            if ([isFriend isEqualToString:@"1"]) {
                NSLog(@"已经是好友");
            } else if ([isFriend isEqualToString:@"0"]) {
                NSLog(@"添加好友");
                FriendIDCheckViewController *friendIDCheckVC = [[FriendIDCheckViewController alloc] init];
                
                friendIDCheckVC.targetUserID = searchModel.user_id;
                friendIDCheckVC.currentUserName = searchModel.nikename;
                [self.navigationController pushViewController: friendIDCheckVC animated:YES];
            }
            break;
        }
        default:
            break;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 75 * kAdjustParamater;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    ZGWSearchFriendModel *model = self.myFriendDataArray[indexPath.row];
    NSLog(@"姓名:%@", model.nikename);
    MyChatViewController *myChatVC = [[MyChatViewController alloc] init];
    myChatVC.conversationType = ConversationType_PRIVATE;
    myChatVC.title = model.nikename;
    myChatVC.targetId = model.user_id;
    [self.navigationController pushViewController:myChatVC animated:YES];
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (self.isHaveData == YES) {
        UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 35 * kAdjustParamater)];
        view.backgroundColor = [UIColor whiteColor];
        
        UILabel *linkPeopleLabel = [[UILabel alloc] initWithFrame:CGRectMake(16 * kAdjustParamater, 12 * kAdjustParamater, 100 * kAdjustParamater, 15 * kAdjustParamater)];
        //    linkPeopleLabel.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.1];
        linkPeopleLabel.text = @"成员搜索结果";
        linkPeopleLabel.textAlignment = NSTextAlignmentLeft;
        linkPeopleLabel.textColor = [[UIColor blackColor] colorWithAlphaComponent:0.5];
        linkPeopleLabel.font = [UIFont systemFontOfSize:k15Big];
        [view addSubview:linkPeopleLabel];
        
        UILabel *grayLine = [[UILabel alloc] initWithFrame:CGRectMake(0, linkPeopleLabel.bottom + 7 * kAdjustParamater, kScreenWidth, 1 * kAdjustParamater)];
        grayLine.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.1];
        [view addSubview:grayLine];
        
        return view;
    }
    // 没有数据
    return nil;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (self.isHaveData == YES) {
        return 35 * kAdjustParamater;
    }
    return 0;
}











- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
